<template>
	<view class="order-detail">
		<view class="order-container">
			<scroll-view class="order-scroll" scroll-y refresher-enabled :refresher-triggered="refreshing"
				@refresherrefresh="onRefresh">
				<skeleton-card-list :loading="loading" type="order" :count="3">
					<template v-if="order">
						<view class="logistics-info">
							<!-- 订单状态 -->
							<view class="status-section">
								<view class="status-info">
									<text class="status">{{ orderStatusText }}</text>
									<text class="tip">{{ orderStatusTip }}</text>
									<text class="countdown" v-if="order.status === 0">
										支付剩余时间：{{ countdownText }}
									</text>
								</view>
							</view>

							<!-- 商品信息 -->
							<view class="goods-section">
								<view class="goods-card">
									<image class="goods-image" :src="order.goods.mainImages[0].imageUrl" mode="aspectFill"></image>
									<view class="goods-info">
										<text class="goods-name">{{ order.goods.name }}</text>
										<view class="price-info">
											<!-- 根据支付方式显示不同的价格信息 -->
											<template v-if="order.paymentType === 1">
												<text class="price">{{ order.totalAmount }}</text>
											</template>
											<template v-else-if="order.paymentType === 2">
												<text class="points">{{ order.pointsCount }}<text class="unit">积分</text></text>
											</template>
											<template v-else-if="order.paymentType === 3">
												<text class="mixed-price">
													<text class="points">{{ order.pointsCount }}</text>
													<text class="unit">积分</text>
													<text class="plus">+</text>
													<text class="cash">{{ order.payAmount }}</text>
												</text>
											</template>
											<template v-else-if="order.paymentType === 4">
												<text class="gift-card">{{ order.giftCardCount }}张礼品卡</text>
											</template>
											<template v-else-if="order.paymentType === 5">
												<text class="gift-voucher">{{ order.voucherCount }}张礼品券</text>
											</template>
											<text class="count">x{{ order.goodsCount }}</text>
										</view>
									</view>
								</view>
							</view>

							<!-- 收货地址 -->
							<view class="address-section">
								<view class="address-content">
									<text class="label">收货信息</text>
									<view class="address-info">
										<view class="user-info">
											<text class="name">{{ order.address.receiverName }}</text>
											<text class="phone">{{ order.address.receiverPhone }}</text>
										</view>
										<text class="detail">
											{{ order.address.province }}{{ order.address.city }}{{ order.address.district }}{{
												order.address.detailAddress }}
										</text>
									</view>
								</view>
							</view>

							<!-- 订单信息 -->
							<view class="order-info">
								<view class="info-item">
									<text class="label">订单编号</text>
									<text class="value">{{ order.orderNo }}</text>
								</view>
								<view class="info-item">
									<text class="label">创建时间</text>
									<text class="value">{{ order.createTime }}</text>
								</view>
								<view class="info-item" v-if="order.payTime">
									<text class="label">支付时间</text>
									<text class="value">{{ order.payTime }}</text>
								</view>
								<view class="info-item" v-if="order.finishTime">
									<text class="label">完成时间</text>
									<text class="value">{{ order.finishTime }}</text>
								</view>
								<view class="info-item" v-if="order.cancelTime">
									<text class="label">取消时间</text>
									<text class="value">{{ order.cancelTime }}</text>
								</view>
								<view class="info-item" v-if="order.cancelReason">
									<text class="label">取消原因</text>
									<text class="value">{{ order.cancelReason }}</text>
								</view>
								<view class="info-item" v-if="order.remark">
									<text class="label">备注</text>
									<text class="value">{{ order.remark }}</text>
								</view>
							</view>

							<!-- 支付信息 -->
							<view class="payment-info">
								<view class="info-item" v-if="order.paymentType === 1 || order.paymentType === 3">
									<text class="label">商品金额</text>
									<text class="value">¥{{ order.totalAmount }}</text>
								</view>
								<view class="info-item" v-if="order.paymentType === 2 || order.paymentType === 3">
									<text class="label">积分抵扣</text>
									<text class="value">{{ order.pointsDeduct }}积分</text>
								</view>
								<view class="info-item" v-if="order.shippingFee">
									<text class="label">运费</text>
									<text class="value">¥{{ order.shippingFee }}</text>
								</view>
								<view class="info-item total">
									<text class="label">实付金额</text>
									<text class="value">
										<template v-if="order.paymentType === 1">
											¥{{ order.payAmount }}
										</template>
										<template v-else-if="order.paymentType === 2">
											{{ order.pointsCount }}积分
										</template>
										<template v-else-if="order.paymentType === 3">
											{{ order.pointsCount }}积分 + ¥{{ order.payAmount }}
										</template>
										<template v-else>
											{{ order.paymentType === 4 ? order.giftCardCount + '张礼品卡' : order.voucherCount + '张礼品券' }}
										</template>
									</text>
								</view>
							</view>

							<!-- 底部按钮 -->
							<view class="action-bar">
								<template v-if="order.status === 0">
									<button class="cancel-btn" @tap="cancelOrder">取消订单</button>
									<button class="pay-btn" @tap="payOrder">立即支付</button>
								</template>
								<template v-else-if="order.status === 6">
									<button class="logistics-btn" @tap="goToLogistics">物流详情</button>
									<button class="confirm-btn" @tap="confirmReceipt">确认收货</button>
								</template>
								<!-- <button v-else-if="order.status === 3" class="delete-btn" @tap="deleteOrder">删除订单</button> -->
							</view>
						</view>
					</template>
				</skeleton-card-list>
			</scroll-view>
		</view>
	</view>
</template>

<script>
import {
	formatDate
} from '@/utils/date.js'
import SkeletonCardList from '@/components/common/skeleton-card-list/skeleton-card-list.vue'

export default {
	components: {
		SkeletonCardList
	},
	data() {
		return {
			loading: true, // 添加骨架屏加载状态
			orderId: null,
			order: null, // 修改默认值为 null
			countdown: 0,
			timer: null,
			refreshing: false
		}
	},

	computed: {
		orderStatusText() {
			if (!this.order) return ''
			const statusMap = {
				0: '待支付',
				1: '已支付',
				2: '已完成',
				3: '已取消',
				4: '已退款',
				5: '超时未支付',
				6: '待收货'
			}
			return statusMap[this.order.status] || '未知状态'
		},

		orderStatusTip() {
			if (!this.order) return ''
			const tipMap = {
				0: '请尽快完成支付',
				1: '商家正在处理订单',
				2: '订单已完成',
				3: '订单已取消',
				4: '订单已退款',
				5: '订单已超时自动取消',
				6: '商家已发货，等待收货'
			}
			return tipMap[this.order.status] || ''
		},

		countdownText() {
			if (this.countdown <= 0) return '已超时'
			const minutes = Math.floor(this.countdown / 60)
			const seconds = this.countdown % 60
			return `${minutes}分${seconds}秒`
		},

		showActions() {
			if (!this.order) return []
			if (this.order.status === 5) {
				return ['delete']
			}

			const actionMap = {
				0: ['cancel', 'pay'],
				1: [],
				2: ['delete'],
				3: ['delete'],
				4: ['delete']
			}
			return actionMap[this.order.status] || []
		}
	},

	onLoad(options) {
		if (options.orderId) {
			this.orderId = options.orderId
			this.loadOrderDetail()
		} else {
			uni.showToast({
				title: '订单信息不完整',
				icon: 'none'
			})
			setTimeout(() => {
				uni.navigateBack()
			}, 1500)
		}
	},

	methods: {
		// 统一处理错误
		handleError(e, defaultMsg) {
			uni.showToast({
				title: e.msg || defaultMsg,
				icon: 'none'
			})
		},

		// 加载订单详情
		async loadOrderDetail() {
			this.loading = true // 显示骨架屏
			try {
				const data = await this.$http.get(`/mall/order/${this.orderId}`)
				if (data) {
					this.order = {
						...data,
						createTime: formatDate(data.createTime, 'YYYY-MM-DD HH:mm:ss'),
						payTime: formatDate(data.payTime, 'YYYY-MM-DD HH:mm:ss'),
						finishTime: formatDate(data.finishTime, 'YYYY-MM-DD HH:mm:ss'),
						cancelTime: formatDate(data.cancelTime, 'YYYY-MM-DD HH:mm:ss')
					}

					if (this.order.status === 0) {
						this.startCountdown()
					}
				}
			} catch (e) {
				this.handleError(e, '获取订单详情失败')
				setTimeout(() => {
					uni.navigateBack()
				}, 1500)
			} finally {
				this.loading = false // 隐藏骨架屏
			}
		},

		// 取消订单
		cancelOrder() {
			uni.showModal({
				title: '提示',
				content: '确定要取消该订单吗？',
				success: async (res) => {
					if (res.confirm) {
						try {
							await this.$http.post(`/mall/order/cancel?orderId=${this.orderId}`)
							this.loadOrderDetail()
						} catch (e) {
							console.error('取消订单失败:', e)
							this.handleError(e, '取消订单失败')
						}
					}
				}
			})
		},

		// 支付订单
		async payOrder() {
			try {
				const paymentDTO = {
					orderId: this.orderId,
					paymentType: this.order.paymentType,
					amount: this.order.payAmount,
					pointsCount: this.order.pointsCount,
					giftCardCount: this.order.giftCardCount,
					voucherCount: this.order.voucherCount
				}

				const result = await this.$http.post('/mall/order/pay/create', paymentDTO)

				if (!result.success) {
					this.handleError({
						msg: result.errorMsg
					}, '支付失败')
					return
				}

				switch (result.status) {
					case 0:  // 微信支付
						if (result.payParams) {
							uni.requestPayment({
								...result.payParams,
								success: () => {
									uni.showToast({
										title: '支付成功',
										icon: 'success'
									})
									this.loadOrderDetail()  // 微信支付成功后刷新
								},
								fail: (err) => {
									console.error('微信支付失败:', err)
									this.handleError(err, '支付失败，请重试')
								}
							})
						}
						break

					case 1:  // 直接支付成功（礼品卡券等）
						uni.showToast({
							title: '支付成功',
							icon: 'success'
						})
						this.loadOrderDetail()  // 直接支付成功后刷新
						break

					case 2:  // 支付失败
						this.handleError({
							msg: result.errorMsg
						}, '支付失败')
						break
				}
			} catch (e) {
				console.error('支付失败:', e)
				this.handleError(e, '支付失败，请重试')
			}
		},

		// 删除订单
		deleteOrder() {
			uni.showModal({
				title: '提示',
				content: '确定要删除该订单吗？',
				success: async (res) => {
					if (res.confirm) {
						try {
							await this.$http.delete(`/mall/order/${this.orderId}`)
							uni.navigateBack()
						} catch (e) {
							this.handleError(e, '删除订单失败')
						}
					}
				}
			})
		},

		// 开始倒计时
		startCountdown() {
			// 清除可能存在的旧定时器
			if (this.timer) {
				clearInterval(this.timer)
			}

			// 计算剩余时间
			const createTime = new Date(this.order.createTime).getTime()
			const now = new Date().getTime()
			const expireTime = createTime + 15 * 60 * 1000 // 15分钟后过期
			this.countdown = Math.max(0, Math.floor((expireTime - now) / 1000))

			// 如果已经超时，设置为超时未支付状态
			if (this.countdown <= 0) {
				this.order.status = 5 // 修改：使用超时未支付状态
				return
			}

			// 启动倒计时
			this.timer = setInterval(() => {
				this.countdown--
				if (this.countdown <= 0) {
					clearInterval(this.timer)
					this.order.status = 5 // 修改：使用超时未支付状态
					// 调用取消订单接口
					this.$http.post(`/mall/order/cancel/${this.orderId}`, {
						cancelReason: '支付超时自动取消'
					}).catch(() => {
						// 忽略错误
					})
				}
			}, 1000)
		},

		// 跳转到物流详情
		goToLogistics() {
			uni.navigateTo({
				url: `/subpkg/logistics_detail/logistics_detail?orderId=${this.orderId}`
			})
		},

		// 确认收货
		confirmReceipt() {
			uni.showModal({
				title: '确认收货',
				content: '确认已收到商品吗？',
				success: async (res) => {
					if (res.confirm) {
						try {
							const result = await this.$http.post(
								`/mall/order/confirm?orderId=${this.orderId}`)
							if (result) {
								uni.showToast({
									title: '确认收货成功',
									icon: 'success'
								})
							}
							this.loadOrderDetail()
						} catch (e) {
							this.handleError(e, '确认收货失败')
						}
					}
				}
			})
		},

		// 下拉刷新
		async onRefresh() {
			this.refreshing = true
			try {
				await this.loadOrderDetail()
			} finally {
				this.refreshing = false
			}
		}
	},

	// 组件销毁时清除定时器
	beforeDestroy() {
		if (this.timer) {
			clearInterval(this.timer)
		}
	}
}
</script>

<style lang="scss" scoped>
@import 'order_detail.scss';

.status-section {
	.status-info {
		.countdown {
			font-size: 24rpx;
			color: #fff;
			opacity: 0.9;
			margin-top: 8rpx;
			display: block;

			&.timeout {
				color: $mall-accent-100;
			}
		}
	}
}
</style>